/** Access Cheval DB through thin driver, and introduce ResultSetMetaData class.
	1. Download thin JDBC driver from Oracle.
	2. ResultSetMetaData interface is implemented by driver provider. The meta data
	   provide methods for accessing properties of table columns such as
		-- nnumber of columns, column names and types,
		-- precision and scale
		-- is column readable, writable, searchable and etc.
	3. DatabaseMeta class provide information about the DBMS (not used in this program).
    The example uses meta data to access number of column of result set and column
headings of a result set.
*/

import java.sql.*;
import java.io.*;

public class AccessChevalDB2 {

	Connection cnn;
	Statement  stmt;
	ResultSet  res;

	String	url = "jdbc:oracle:thin:@cheval.cs.csubak.edu:1521:TEST",
		user="cs440", passwd="student2";

	public AccessChevalDB2() {
	   try {
		// The following two methods of loading JDBC driver are tested and worked
		// Method 1: call Class.forName(), metho 2: call DriverManager.registerDriver().
		// ---------------------------------------------------------------------------
             	try { Class.forName("oracle.jdbc.driver.OracleDriver"); }
		catch (ClassNotFoundException ee) { ee.printStackTrace(); System.exit(-1); }
		// Method 2:
		//  DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
		// ---------------------------------------------------------------------------

		cnn = DriverManager.getConnection(url, user, passwd);
		stmt = cnn.createStatement();
	   } catch (SQLException e ) { e.printStackTrace(); System.exit(-1); }
	}

	public static void main(String argv[]) {
		AccessChevalDB2 ex2 = new AccessChevalDB2(); // get connected, and create stmt.
		byte ans[] = new byte[120];
		char c = ' ';
		String	sql;

		while ( true ) {
			for ( int i = 0; i < ans.length; i ++ ) ans[i] = (byte) ' ';
			sql = ScreenIO.promptForString("Enter a SQL statement or Q/e to quite ... ");
			if ( sql == null || sql.equals("") ) continue;
			try { c = sql.charAt(0); } catch (StringIndexOutOfBoundsException e) {}
			if ( c == 'q' || c == 'Q' ) { ex2.deallocateResources();  System.exit(0); }
			try { ex2.res = ex2.stmt.executeQuery(sql); } catch (SQLException e) {}
			System.out.println();
			ScreenIO.displayResultSet(ex2.res);
		}
	}

	void deallocateResources() {
	   try {
		stmt.close();
		res.close();
		cnn.close();
	   } catch (SQLException e) {}
	   try { super.finalize(); } catch (Throwable e) {}
	}
}
